package com.xj.shop.manage.all.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xj.shop.enums.Shop;
import com.xj.shop.manage.all.mapper.GoodsMapper;
import com.xj.shop.manage.all.model.dto.GoodsDTO;
import com.xj.shop.manage.all.model.dto.GoodsSpecsDTO;
import com.xj.shop.manage.all.model.entity.Category;
import com.xj.shop.manage.all.model.entity.Goods;
import com.xj.shop.manage.all.model.query.GoodsQuery;
import com.xj.shop.manage.all.model.vo.GoodsVO;
import com.xj.shop.manage.all.service.CategoryService;
import com.xj.shop.manage.all.service.GoodsService;
import com.xj.shop.manage.all.service.GoodsSpecsService;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.core.utils.BeanDtoVoUtil;
import io.github.wslxm.springbootplus2.core.utils.validated.ValidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 商品表 ServiceImpl
 *
 * <p>
 * ::本代码由[兮家小二]提供的代码生成器生成,如有问题,请手动修改 ::作者CSDN:https://blog.csdn.net/qq_41463655
 * </p>
 * @author ws
 * @email 1720696548@qq.com
 * @date 2022-08-24 18:54:32
 */
@Service
public class GoodsServiceImpl extends BaseServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsSpecsService goodsSpecsService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public IPage<GoodsVO> findPage(GoodsQuery query) {
        Page<GoodsVO> page = new Page<>(query.getCurrent(), query.getSize());
        page.setRecords(baseMapper.list(page, query));
        // 填充类别数据
        this.fillCategoryName(page.getRecords());
        return page;
    }

    @Override
    public GoodsVO findId(String id) {
        GoodsVO goodsVo = BeanDtoVoUtil.convert(this.getById(id), GoodsVO.class);
        ValidUtil.isTrue(goodsVo==null,"没有找到商品信息");
        goodsVo.setGoodsSpecsList(goodsSpecsService.findByGoodsId(id));
        // 填充类别数据
        this.fillCategoryName(CollUtil.newArrayList(goodsVo));
        return goodsVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insert(GoodsDTO dto) {
        // 添加商品
        Goods entity = dto.convert(Goods.class);
        // 处理分类
        String[] categoryIdsArray = entity.getCategoryIds().split(",");
        entity.setCategoryOne(categoryIdsArray.length > 0 ? categoryIdsArray[0] : null);
        entity.setCategoryTwo(categoryIdsArray.length > 1 ? categoryIdsArray[1] : null);
        entity.setCategoryThree(categoryIdsArray.length > 2 ? categoryIdsArray[2] : null);

        // 获取最低最高价
        List<GoodsSpecsDTO> goodsSpecsList = ListUtil.sortByProperty(dto.getGoodsSpecsList(), "sort");
        entity.setMinPrice(goodsSpecsList.get(goodsSpecsList.size() - 1).getSpecsPrice());
        entity.setMaxPrice(goodsSpecsList.get(0).getSpecsPrice());

        // 保存
        boolean b = this.save(entity);

        // 添加规格信息
        goodsSpecsService.updGoodsSpecsBatch(dto.getGoodsSpecsList(), entity.getId());
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upd(String id, GoodsDTO dto) {
        // 商品下架才有编辑
        this.verifyState(id, Shop.GoodsState.V0.getValue());
        // 数据处理
        Goods entity = dto.convert(Goods.class);
        entity.setId(id);
        // 处理分类
        String[] categoryIdsArray = entity.getCategoryIds().split(",");
        entity.setCategoryOne(categoryIdsArray.length > 0 ? categoryIdsArray[0] : null);
        entity.setCategoryTwo(categoryIdsArray.length > 1 ? categoryIdsArray[1] : null);
        entity.setCategoryThree(categoryIdsArray.length > 2 ? categoryIdsArray[2] : null);

        // 获取最低最高价
        List<GoodsSpecsDTO> goodsSpecsList = ListUtil.sortByProperty(dto.getGoodsSpecsList(), "sort");
        entity.setMinPrice(goodsSpecsList.get(goodsSpecsList.size() - 1).getSpecsPrice());
        entity.setMaxPrice(goodsSpecsList.get(0).getSpecsPrice());

        boolean b = this.updateById(entity);
        // 处理规格数据
        goodsSpecsService.updGoodsSpecsBatch(dto.getGoodsSpecsList(), entity.getId());
        return  true;
    }

    @Override
    public boolean del(String id) {
        // 商品下架才有删除
        this.verifyState(id, Shop.GoodsState.V0.getValue());
        return this.removeById(id);
    }

    @Override
    public boolean updState(String id, Integer state) {
        Goods updGoods = new Goods();
        updGoods.setState(state);
        updGoods.setId(id);
        return this.updateById(updGoods);
    }

    /**
     * 验证商品状态
     * 是否下架中，是否上架中
     * @author wangsong
     * @param goodsId
     * @date 2022/8/24 0024 23:34
     * @return void
     * @version 1.0.0
     */
    private void verifyState(String goodsId, Integer state) {
        long count = this.count(new LambdaQueryWrapper<Goods>()
                .eq(Goods::getState, state)
                .eq(Goods::getId, goodsId));
        if (state.equals(Shop.GoodsState.V0.getValue())) {
            ValidUtil.isTrue(count == 0, "商品未处于下架状态");
        } else if (state.equals(Shop.GoodsState.V1.getValue())) {
            ValidUtil.isTrue(count == 0, "商品未处于上架状态");
        }
    }


    /**
     * 填充类别数据
     *
     * @return void
     * @author wangsong
     * @date 2022/8/25 11:47
     */
    private void fillCategoryName(List<GoodsVO> goodsVos) {
        // 获取商品类别Id Set去重
        Set<String> categoryIds = new HashSet<>();
        for (GoodsVO goodsVO : goodsVos) {
            if (goodsVO.getCategoryOne() != null) {
                categoryIds.add(goodsVO.getCategoryOne());
            }
            if (goodsVO.getCategoryTwo() != null) {
                categoryIds.add(goodsVO.getCategoryTwo());
            }
            if (goodsVO.getCategoryThree() != null) {
                categoryIds.add(goodsVO.getCategoryThree());
            }
        }
        if(categoryIds.size()==0){
            return;
        }
        // 获取商品类别数据
        List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>().in(Category::getId, categoryIds));
        if (categoryList.size() > 0) {
            Map<String, Category> categoryMap = categoryList.stream().collect(Collectors.toMap(Category::getId, p -> p));
            // 填充数据
            for (GoodsVO goodsVO : goodsVos) {
                if (goodsVO.getCategoryOne() != null) {
                    goodsVO.setCategoryOneName(categoryMap.get(goodsVO.getCategoryOne()).getName());
                }
                if (goodsVO.getCategoryTwo() != null) {
                    goodsVO.setCategoryTwoName(categoryMap.get(goodsVO.getCategoryTwo()).getName());
                }
                if (goodsVO.getCategoryThree() != null) {
                    goodsVO.setCategoryThreeName(categoryMap.get(goodsVO.getCategoryThree()).getName());
                }
            }
        }
    }
}
